<template>
  <div class="order-container">
    <order-header></order-header>
    <div class="order-holder">
      <h1 class="order-title">订单详情</h1>
      <div v-if="shoppingCart !== null" v-for="cartItem in shoppingCart" :key="cartItem.product.id" class="order-products">
        <img v-if="cartItem.product.haspicture === 1" class="order-products-img" :src="productPictureUrl + cartItem.product.id">
        <div class="order-products-name">{{ cartItem.product.name }}</div>
        <div class="order-products-amount">{{ cartItem.product.price }}元 × {{ cartItem.amount }}</div>
        <div class="order-products-cost">{{ (cartItem.product.price * cartItem.amount).toFixed(1) }}元</div>
      </div>
      <div class="order-address">
        <div class="order-address-title">收货信息</div>
        <div class="order-address-info">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名：&nbsp;&nbsp;&nbsp;{{ nowUser.username }}</div>
        <div class="order-address-info">联系电话：&nbsp;&nbsp;&nbsp;{{ userInfo.phone }}</div>
        <div class="order-address-info">收货地址：&nbsp;&nbsp;&nbsp;{{ userInfo.address }}</div>
      </div>
      <div class="order-pay">
        <div class="order-pay-title">支付方式</div>
        <div class="order-pay-info">支付方式：&nbsp;&nbsp;&nbsp;APP内支付</div>
        <div class="order-pay-info">支付提醒：&nbsp;&nbsp;&nbsp;当快递员接单后，您会在APP内接收到支付提醒</div>
      </div>
      <div class="order-cost">
        <div class="order-cost-info">商品总价：&nbsp;&nbsp;&nbsp;
          <span style="color:#ff6700;">{{ shoppingCartTotalCost }}元</span>
        </div>
        <div class="order-cost-info">快递运费：&nbsp;&nbsp;&nbsp;
          <span style="color:#ff6700;">{{ deliveryCost }}元&nbsp;&nbsp;&nbsp;(商店据您的收货地址{{ deliveryDistance }}米)</span>
        </div>
        <div class="order-cost-total">总&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;计：&nbsp;&nbsp;&nbsp;
          <span style="font-size:30px;color:#ff6700;">{{ totalCost }}</span>
          <span style="color:#ff6700;">元</span>
          <el-button style="float:right;" type="danger" @click="confirmOrder">确认下单</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ROUTENAME } from 'services/constConfig.js'
import { mapGetters, mapActions } from 'vuex'
import { FileApi, OrderApi } from 'services/apiConfig.js'
import OrderHeader from 'components/Header.vue'
import orderService from 'services/orderService.js'
import positionService from 'services/positionService.js'
import userService from 'services/userService.js'
import userinfoService from 'services/userinfoService.js'
import notificationService from 'services/notificationService.js'
import * as notifyUtil from 'utils/notifyUtil.js'
import AMap from 'AMap'

export default {
  components: {
    'order-header': OrderHeader
  },
  data() {
    return {
      productPictureUrl: FileApi.product.getUrl,
      userInfo: {
        phone: '',
        wechat: '',
        address: ''
      },
      geocoder: null,
      geometryUtil: null,
      deliveryDistance: 0,
      lnglat: new AMap.LngLat(121.41956, 31.014372),
      choosedUser: {
        result: 0,
        // userId: 1514123810491
        userId: 0
      },
      choosedNum: 0,
      totalNum: 0
    }
  },
  computed: {
    ...mapGetters({
      nowStore: 'nowStore',
      nowUser: 'nowUser',
      shoppingCart: 'shoppingCart',
      shoppingCartTotalCost: 'shoppingCartTotalCost'
    }),
    deliveryCost: function() {
      return (10 + this.deliveryDistance / 1000 * 3).toFixed(2)
    },
    totalCost: function() {
      return (this.shoppingCartTotalCost + parseFloat(this.deliveryCost)
      ).toFixed(2)
    }
  },
  methods: {
    ...mapActions({}),
    subscribeOrder(orderId) {
      let source = new EventSource(
        OrderApi.subscribeOrder.url + orderId + '/syncronize'
      )
      source.onmessage = function(event) {
        console.log(event.data)
        let tempOrder = JSON.parse(event.data)
        if (tempOrder.status === 6) {
          notifyUtil.showSuccess('订单状态更新', '您的订单已被接单')
        }
        if (tempOrder.status === 8) {
          notifyUtil.showSuccess('订单状态更新', '您的订单已确认送达')
        }
      }
    },
    confirmOrder() {
      if (this.choosedNum >= this.totalNum) {
        if (this.choosedUser.userId <= 0) {
          notifyUtil.showInfo('下单失败', '您的周围暂无满足条件的快递员，请稍后再试')
        } else {
          this.addOrder()
        }
      } else {
        notifyUtil.showInfo('正在为您寻找快递员', '请稍后再试')
      }
    },
    addOrder() {
      let order = {
        senderid: this.nowStore.userid,
        courierid: 0,
        receiverid: this.nowUser.id,
        productcost: this.shoppingCartTotalCost,
        deliverycost: parseFloat(this.deliveryCost),
        totalcost: parseFloat(this.totalCost),
        status: 0,
        createtime: new Date().valueOf(),
        shopid: this.nowStore.id,
        shopname: this.nowStore.name
      }
      orderService.addOrder(order).then(response => {
        if (response.data.id === null || response.data.id === undefined) {
          notifyUtil.showError('下单失败', '服务器错误')
        } else {
          // this.subscribeOrder(response.data.id)
          this.addOrderItem(response.data.id)
          // this.$router.push({ path: ROUTENAME.USER_ORDER })
          this.getNotification(this.choosedUser.userId, response.data.id)
        }
      })
    },
    addOrderItem(orderId) {
      for (let item in this.shoppingCart) {
        let itemValue = this.shoppingCart[item]
        let orderItem = {
          orderid: orderId,
          productid: itemValue.product.id,
          productname: itemValue.product.name,
          productprice: itemValue.product.price,
          amount: itemValue.amount
        }
        orderService.addOrderItem(orderItem).then(response => {
          if (response.data.id === null || response.data.id === undefined) {
            notifyUtil.showError('添加订单项失败', '服务器错误')
          } else {
            // this.$router.push({ path: ROUTENAME.USER_ORDER })
          }
        })
      }
    },
    chooseNotificationUser() {
      userService.getAllUsers().then(response => {
        if (response.data.User === null || response.data.User === undefined) {
          notifyUtil.showInfo('周围暂无用户', '请稍后再试')
        } else {
          this.$set(this, 'totalNum', response.data.User.length)
          console.log(this.totalNum)
          for (let index = 0; index < response.data.User.length; index++) {
            let user = response.data.User[index]
            // this.getUserPosition(user.id)
            this.getAccessableNotification(user.id)
          }
        }
      })
    },
    getAccessableNotification(userId) {
      notificationService.getAccessableNotification(userId).then(response => {
        if (
          response.data.Notification === null ||
          response.data.Notification === undefined
        ) {
          // notifyUtil.showError('下单失败', '目的地周围暂无快递员可接单')
          this.$set(this, 'choosedNum', this.choosedNum + 1)
          console.log('getAccessableNotification---' + this.choosedNum)
        } else {
          this.getUserPosition(userId)
        }
      })
    },
    getUserPosition(userId) {
      positionService.getPosition(userId).then(response => {
        if (
          response.data.Position === null ||
          response.data.Position === undefined
        ) {
          notifyUtil.showInfo('您附近暂无快递员', '请稍后再试')
          this.$set(this, 'choosedNum', this.choosedNum + 1)
          console.log('getUserPosition---' + this.choosedNum)
        } else {
          let userPosition = response.data.Position[0]
          // console.log(userPosition)
          let distance = this.lnglat.distance([
            userPosition.lontitude,
            userPosition.latitude
          ])
          if (distance <= 100000) {
            this.getUserOrderHistory(userId, distance)
          } else {
            this.$set(this, 'choosedNum', this.choosedNum + 1)
            console.log('getUserPosition > 10km---' + this.choosedNum)
          }
        }
      })
    },
    getUserOrderHistory(userId, distance) {
      orderService.getOrdersByCourierId(userId).then(response => {
        if (response.data.Order === null || response.data.Order === undefined) {
        } else {
          let result = 0.5 * distance / 1000 + response.data.Order.length * 0.5
          if (result > this.choosedUser.result) {
            this.$set(this.choosedUser, 'result', result)
            this.$set(this.choosedUser, 'userId', userId)
          }
        }
        this.$set(this, 'choosedNum', this.choosedNum + 1)
        console.log('getUserOrderHistory---' + this.choosedNum)
      })
    },
    getNotification(userId, orderId) {
      notificationService.getNotification(userId).then(response => {
        if (
          response.data.Notification === null ||
          response.data.Notification === undefined
        ) {
          notifyUtil.showError('获取通知信息失败', '服务器错误')
        } else {
          this.updateNotification(response.data.Notification[0], orderId)
        }
      })
    },
    updateNotification(notification, orderId) {
      let updatedNotification = {
        id: notification.id,
        userid: notification.userid,
        orderid: orderId,
        accessiblity: 0,
        latestupdate: new Date().valueOf()
      }
      notificationService
        .updateNotification(updatedNotification)
        .then(response => {
          if (response.data.id === null || response.data.id === undefined) {
            notifyUtil.showError('通知失败', '服务器错误')
          } else {
            notifyUtil.showSuccess('下单成功', '请等待快递员接单')
            this.$router.push({
              path: ROUTENAME.USER_ORDER,
              query: {
                orderId: orderId
              }
            })
          }
        })
    },
    getUserInfo() {
      userinfoService.getUserInfo(this.nowUser.id).then(response => {
        if (
          response.data.Userinfo === null ||
          response.data.Userinfo === undefined
        ) {
          notifyUtil.showError('获取用户信息失败', '服务器错误')
        } else {
          this.$set(this.userInfo, 'phone', response.data.Userinfo[0].phone)
          this.$set(this.userInfo, 'wechat', response.data.Userinfo[0].wechat)
          this.$set(this.userInfo, 'address', response.data.Userinfo[0].address)
          this.calcDeliveryDistance()
        }
      })
    },
    calcDeliveryDistance() {
      this.geocoder.getLocation(this.userInfo.address, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // let pos1 = [this.nowStore.longitude, this.nowStore.latitude]
          // let pos2 = [
          //   result.geocodes[0].location.lng,
          //   result.geocodes[0].location.lat
          // ]
          let lnglat = new AMap.LngLat(
            this.nowStore.longitude,
            this.nowStore.latitude
          )
          let distance = lnglat.distance([
            result.geocodes[0].location.lng,
            result.geocodes[0].location.lat
          ])
          this.$set(this, 'deliveryDistance', distance.toFixed(2))
        } else {
          notifyUtil.showError('定位失败', '请退出后重试')
        }
      })
    }
  },
  mounted() {
    this.getUserInfo()
    AMap.service('AMap.Geocoder', () => {
      this.geocoder = new AMap.Geocoder({})
    })
    this.chooseNotificationUser()
  },
  watch: {}
}
</script>

<style scoped>
.order-container {
  position: absolute;
  width: 100%;
  height: 100%;
  bottom: 0;
  background-color: #f7f7f7;
}
.order-holder {
  margin-top: 30px;
  width: 1200px;
  /* height: 800px; */
  margin-left: auto;
  margin-right: auto;
  background-color: #ffffff;
  box-sizing: border-box;
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 36px;
  padding-bottom: 36px;
}
.order-products {
  /* margin-top: 30px; */
  width: 100%;
  height: 80px;
  line-height: 80px;
  text-align: left;
  font-size: 14px;
  color: #333;
  margin-left: 0;
  margin-right: 0;
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
}
.order-products-img {
  margin-left: 20px;
  margin-top: 10px;
  width: 60px;
  height: 60px;
  float: left;
}
.order-products-name {
  width: 400px;
  height: 80px;
  float: left;
  margin-left: 36px;
  line-height: 80px;
  text-align: left;
  font-size: 14px;
}
.order-products-amount {
  width: 200px;
  height: 80px;
  float: left;
  line-height: 80px;
  text-align: left;
  font-size: 14px;
}
.order-products-cost {
  width: 200px;
  height: 80px;
  float: left;
  line-height: 80px;
  text-align: left;
  font-size: 14px;
}
.order-title {
  text-align: left;
  margin: 0;
  font-size: 30px;
  font-weight: 400;
  line-height: 68px;
  color: #757575;
  border-bottom: 1px solid #e0e0e0;
}
.order-address {
  margin-top: 30px;
  width: 100%;
  text-align: left;
  font-size: 14px;
  color: #333;
  margin-left: 0;
  margin-right: 0;
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
}
.order-address-title {
  width: 100%;
  height: 30px;
  margin-bottom: 10px;
  line-height: 30px;
  text-align: left;
  font-size: 18px;
}
.order-address-info {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: left;
  color: #757575;
  font-size: 14px;
}
.order-pay {
  margin-top: 30px;
  width: 100%;
  text-align: left;
  font-size: 14px;
  color: #333;
  margin-left: 0;
  margin-right: 0;
  background-color: #ffffff;
  border-bottom: 1px solid #e0e0e0;
}
.order-pay-title {
  width: 100%;
  height: 30px;
  margin-bottom: 10px;
  line-height: 30px;
  text-align: left;
  font-size: 18px;
}
.order-pay-info {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: left;
  color: #757575;
  font-size: 14px;
}
.order-cost {
  margin-top: 30px;
  width: 100%;
  text-align: right;
  font-size: 14px;
  color: #333;
  margin-left: 0;
  margin-right: 0;
  background-color: #ffffff;
}
.order-cost-info {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: left;
  color: #757575;
  font-size: 14px;
}
.order-cost-total {
  margin-top: 25px;
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: left;
  color: #757575;
  font-size: 14px;
}
</style>
